<template>
  <div class="review-system-container">
    <!-- 1. 评委登录验证弹窗 -->
    <el-dialog
        title="评委身份验证"
        :visible.sync="loginDialogVisible"
        width="420px"
        top="20%"
        :close-on-click-modal="false"
        :show-close="false"
        :modal="true"
    >
      <el-form
          ref="loginForm"
          :model="loginForm"
          label-width="100px"
          :rules="loginRules"
          class="login-form"
      >
        <el-form-item label="评审编码" prop="judgeCode">
          <el-input
              v-model="loginForm.judgeCode"
              placeholder="请输入评审编码"
              autocomplete="off"
          />
        </el-form-item>
        <el-form-item>
          <el-button
              type="primary"
              @click="handleLogin"
              style="width: 100%;"
              :loading="loginLoading"
          >
            验证并进入评审
          </el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 2. 已登录状态页面 -->
    <div v-if="isLogin" class="main-content">
      <!-- 顶部导航栏 -->
      <header class="top-nav">
        <div class="logo-title">
          <h1>吉林油田科研项目评审系统</h1>
        </div>
        <div class="user-info-container">
          <el-dropdown @command="handleUserCommand">
            <span class="user-info">
              <i class="el-icon-user-circle"></i>
              <span class="username">{{ currentUser.name }}</span>
              <span class="specialty-tag">{{ currentUser.specialty }}</span>
              <i class="el-icon-arrow-down el-icon--right"></i>
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="logout" divided>
                <i class="el-icon-switch-button"></i> 退出登录
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </div>
      </header>

      <!-- 页面标题和说明 -->
      <div class="page-header">
        <h2>项目评审工作区</h2>
        <p class="page-description">
          请对以下分配给您的{{ currentUser.specialty }}专业组项目进行评审打分
        </p>
      </div>

      <!-- 筛选和排序区 -->
      <div class="filter-sort-bar">
        <div class="filter-group">
          <!-- 评审状态筛选 -->
          <el-select
              v-model="filterStatus"
              placeholder="评审状态"
              style="width: 160px; margin-right: 15px;"
              @change="handleFilterChange"
          >
            <el-option label="全部项目" value="all"></el-option>
            <el-option label="未评审" value="unreviewed"></el-option>
            <el-option label="已评审" value="reviewed"></el-option>
          </el-select>

          <!-- 项目搜索 -->
          <el-input
              v-model="searchKeyword"
              placeholder="搜索项目名称..."
              prefix-icon="el-icon-search"
              style="width: 300px;"
              @input="handleSearch"
          ></el-input>
        </div>

        <!-- 排序控制 -->
        <div class="sort-group">
          <el-select
              v-model="sortType"
              placeholder="排序方式"
              style="width: 200px;"
              @change="handleSortChange"
          >
            <el-option label="默认顺序" value="default"></el-option>
            <el-option label="申报等级（高→低）" value="level_desc"></el-option>
            <el-option label="申报等级（低→高）" value="level_asc"></el-option>
            <el-option label="评审分数（高→低）" value="score_desc" v-if="hasReviewedProjects"></el-option>
            <el-option label="评审分数（低→高）" value="score_asc" v-if="hasReviewedProjects"></el-option>
          </el-select>
        </div>
      </div>

      <!-- 评审进度概览 -->
      <div class="review-progress">
        <div class="progress-info">
          <span>评审进度：</span>
          <span class="completed-count">{{ completedReviewCount }}</span>
          <span>/</span>
          <span class="total-count">{{ filteredProjects.length }}</span>
          <span>个项目</span>
        </div>
        <el-progress
            :percentage="reviewProgressPercentage"
            :stroke-width=6
            :status="isAllReviewed ? 'success' : undefined"
            style="flex: 1; margin: 0 15px;"
        ></el-progress>
        <el-button
            type="primary"
            icon="el-icon-check"
            @click="submitAllReviews"
            :disabled="!isAllReviewed || isAllSubmitted"
            :loading="submitLoading"
        >
          全部提交
        </el-button>
      </div>

      <!-- 项目列表 -->
      <div class="project-list-container">
        <el-table
            :data="filteredProjects"
            border
            style="width: 100%;"
            :row-class-name="tableRowClassName"
            :highlight-current-row="true"
        >
          <el-table-column
              type="index"
              label="序号"
              width="60">
          </el-table-column>
          <el-table-column
              prop="projectName"
              label="项目名称"
              min-width="300">
          </el-table-column>
          <el-table-column
              prop="declareLevel"
              label="申报等级">
            <template slot-scope="scope">
              <el-tag :type="getLevelTagType(scope.row.declareLevel)">
                {{ scope.row.declareLevel }}
              </el-tag>
            </template>
          </el-table-column>
          <!-- 新增三个打分项字段 -->
          <el-table-column
              prop="bgScore"
              label="立项背景得分">
            <template slot-scope="scope">
              <span v-if="scope.row.bgScore !== null" class="reviewed-score">{{ scope.row.bgScore }}</span>
              <span v-else class="unreviewed-score">-</span>
            </template>
          </el-table-column>
          <el-table-column
              prop="innovationScore"
              label="创新点得分">
            <template slot-scope="scope">
              <span v-if="scope.row.innovationScore !== null" class="reviewed-score">{{ scope.row.innovationScore }}</span>
              <span v-else class="unreviewed-score">-</span>
            </template>
          </el-table-column>
          <el-table-column
              prop="economicScore"
              label="经济效益得分">
            <template slot-scope="scope">
              <span v-if="scope.row.economicScore !== null" class="reviewed-score">{{ scope.row.economicScore }}</span>
              <span v-else class="unreviewed-score">-</span>
            </template>
          </el-table-column>
          <el-table-column
              prop="totalScore"
              label="总分"
              width="120">
            <template slot-scope="scope">
              <span v-if="scope.row.totalScore !== '-'" class="reviewed-score">{{ scope.row.totalScore }}</span>
              <span v-else class="unreviewed-score">-</span>
            </template>
          </el-table-column>
          <el-table-column
              prop="status"
              label="评审状态">
            <template slot-scope="scope">
              <el-tag :type="scope.row.status === '已评审' ? 'success' : scope.row.status === '已提交' ? 'info' : 'warning'">
                <i :class="scope.row.status === '已评审' ? 'el-icon-check' : scope.row.status === '已提交' ? 'el-icon-check-circle' : 'el-icon-time'"></i>
                {{ scope.row.status }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column
              label="操作"
              width="120">
            <template slot-scope="scope">
              <el-button
                  size="mini"
                  type="primary"
                  @click="openReviewDrawer(scope.row, $event)"
                  :icon="scope.row.status === '已提交' ? 'el-icon-view' : 'el-icon-edit'"
                  icon-position="left"
              >
                {{ scope.row.status === '已提交' ? '查看' : (scope.row.status === '已评审' ? '编辑' : '评审') }}
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 空状态提示 -->
        <div v-if="filteredProjects.length === 0" class="empty-state">
          <el-empty
              description="当前没有符合条件的项目"
          ></el-empty>
        </div>
      </div>

      <!-- 3. 右侧评审抽屉 - 优化版 -->
      <el-drawer
          :title="null"
      :visible.sync="reviewDrawerVisible"
      :direction="'rtl'"
      size='80%'
      :destroy-on-close="true"
      >
      <div v-if="currentProject" class="review-drawer-content">
        <!-- 1. 优化：将标题、项目名称和状态放在一行显示 -->
        <div class="drawer-header">
          <h3 class="drawer-title">项目评审详情</h3>
          <div class="project-info-row">
            <span class="project-name">{{ currentProject.projectName }}</span>
            <el-tag
                :type="currentProject.status === '已评审' ? 'success' : currentProject.status === '已提交' ? 'info' : 'warning'"
                class="project-status-tag"
            >
              {{ currentProject.status }}
            </el-tag>
          </div>
        </div>

        <!-- 移除了项目基本信息部分 -->

        <!-- 评审内容与打分项组合区域 -->
        <div class="review-content-wrapper">
          <!-- 立项背景与对应打分项 -->
          <div class="review-section">
            <h4 class="section-title">
              <i class="el-icon-document"></i> 项目背景（对应：业务需求）
            </h4>

            <div class="review-section-content">
              <!-- 项目内容与评分输入 -->
              <div class="content-score-container">
                <el-card class="detail-card">
                  <p class="preformatted-text">{{ currentProject.projectBg }}</p>
                </el-card>

                <div class="score-panel">
                  <el-form :model="reviewForm">
                    <el-form-item label="立项背景得分（0-30分）">
                      <el-input-number
                          v-model="reviewForm.bgScore"
                          :min="0"
                          :max="30"
                          :step="0.5"
                          :precision="1"
                          @change="calculateTotalScore"
                          :disabled="currentProject.status === '已提交'"
                          class="score-input"
                      ></el-input-number>
                      <div class="score-display">
                        <span class="score-max">当前: {{ reviewForm.bgScore }}/30</span>

                        <!-- 2. 优化：使用el-popover显示评分标准 -->
                        <el-popover
                            placement="bottom"
                            width="600"
                            trigger="click"
                            popper-class="criteria-popover"
                        >
                          <div slot="reference" class="criteria-trigger">
                            <i class="el-icon-info-circle"></i> 评分标准
                          </div>
                          <div class="scoring-criteria-popover">
                            <h5 class="criteria-title">评分标准（业务需求 - 20%）</h5>
                            <div class="criteria-table-wrapper">
                              <table class="criteria-table">
                                <thead>
                                <tr>
                                  <th>等级</th>
                                  <th>分数范围</th>
                                  <th>评分标准</th>
                                </tr>
                                </thead>
                                <tbody>
                                <tr>
                                  <td>Ⅰ</td>
                                  <td>9~10分</td>
                                  <td>成果直接支撑公司主营业务发展，显著提升业务竞争力，或对未来新兴业务具有极强的引领作用，预期将带来重大业务变革。</td>
                                </tr>
                                <tr>
                                  <td>Ⅱ</td>
                                  <td>7~8分</td>
                                  <td>成果对公司主营业务发展有重要支持作用，或对未来新兴业务有显著推动作用。</td>
                                </tr>
                                <tr>
                                  <td>Ⅲ</td>
                                  <td>5~6分</td>
                                  <td>成果对公司业务有一定支持作用，但影响相对有限。</td>
                                </tr>
                                <tr>
                                  <td>Ⅳ</td>
                                  <td>0~4分</td>
                                  <td>成果对公司业务影响较小，或尚未体现明显支持作用。</td>
                                </tr>
                                </tbody>
                              </table>
                            </div>
                          </div>
                        </el-popover>
                      </div>
                    </el-form-item>
                  </el-form>
                </div>
              </div>
            </div>
          </div>

          <!-- 创新点与对应打分项 -->
          <div class="review-section">
            <h4 class="section-title">
              <i class="el-icon-sunny"></i> 创新点（对应：创造性）
            </h4>

            <div class="review-section-content">
              <div class="content-score-container">
                <el-card class="detail-card">
                  <p class="preformatted-text">{{ currentProject.innovation }}</p>
                </el-card>

                <div class="score-panel">
                  <el-form :model="reviewForm">
                    <el-form-item label="创新点得分（0-35分）">
                      <el-input-number
                          v-model="reviewForm.innovationScore"
                          :min="0"
                          :max="35"
                          :step="0.5"
                          :precision="1"
                          @change="calculateTotalScore"
                          :disabled="currentProject.status === '已提交'"
                          class="score-input"
                      ></el-input-number>
                      <div class="score-display">
                        <span class="score-max">当前: {{ reviewForm.innovationScore }}/35</span>

                        <!-- 评分标准弹窗 -->
                        <el-popover
                            placement="bottom"
                            width="600"
                            trigger="click"
                            popper-class="criteria-popover"
                        >
                          <div slot="reference" class="criteria-trigger">
                            <i class="el-icon-info-circle"></i> 评分标准
                          </div>
                          <div class="scoring-criteria-popover">
                            <h5 class="criteria-title">评分标准（创造性 - 40%）</h5>
                            <div class="criteria-table-wrapper">
                              <table class="criteria-table">
                                <thead>
                                <tr>
                                  <th>等级</th>
                                  <th>分数范围</th>
                                  <th>评分标准</th>
                                </tr>
                                </thead>
                                <tbody>
                                <tr>
                                  <td>Ⅰ</td>
                                  <td>9~10分</td>
                                  <td>在关键技术或者系统集成上有特别重大创新或突破，技术难度大</td>
                                </tr>
                                <tr>
                                  <td>Ⅱ</td>
                                  <td>7~8分</td>
                                  <td>在关键技术或者系统集成上有重大创新或突破，技术难度较大</td>
                                </tr>
                                <tr>
                                  <td>Ⅲ</td>
                                  <td>5~6分</td>
                                  <td>在关键技术或者系统集成上有较大创新或突破，技术难度适中</td>
                                </tr>
                                <tr>
                                  <td>Ⅳ</td>
                                  <td>0~4分</td>
                                  <td>在关键技术或者系统集成上有创新或突破，技术获取与技术开发有一定难度</td>
                                </tr>
                                <tr>
                                  <td colspan="3" class="sub-criteria-title">先进性</td>
                                </tr>
                                <tr>
                                  <td>Ⅰ</td>
                                  <td>9~10分</td>
                                  <td>总体技术和主要技术经济指标达到或超过集团公司内部技术或产品的领先水平</td>
                                </tr>
                                <tr>
                                  <td>Ⅱ</td>
                                  <td>7~8分</td>
                                  <td>总体技术和主要技术经济指标达到或超过集团公司内部技术或产品的先进水平</td>
                                </tr>
                                <tr>
                                  <td>Ⅲ</td>
                                  <td>5~6分</td>
                                  <td>总体技术和主要技术经济指标达到或超过公司技术或产品的领先水平</td>
                                </tr>
                                <tr>
                                  <td>Ⅳ</td>
                                  <td>0~4分</td>
                                  <td>总体技术和主要技术经济指标达到或超过公司技术或产品的先进水平</td>
                                </tr>
                                </tbody>
                              </table>
                            </div>
                          </div>
                        </el-popover>
                      </div>
                    </el-form-item>
                  </el-form>
                </div>
              </div>
            </div>
          </div>

          <!-- 经济效益与对应打分项 -->
          <div class="review-section">
            <h4 class="section-title">
              <i class="el-icon-money"></i> 经济效益（对应：效益性）
            </h4>

            <div class="review-section-content">
              <div class="content-score-container">
                <el-card class="detail-card">
                  <p class="preformatted-text">{{ currentProject.economicBenefit }}</p>
                </el-card>

                <div class="score-panel">
                  <el-form :model="reviewForm">
                    <el-form-item label="经济效益得分（0-35分）">
                      <el-input-number
                          v-model="reviewForm.economicScore"
                          :min="0"
                          :max="35"
                          :step="0.5"
                          :precision="1"
                          @change="calculateTotalScore"
                          :disabled="currentProject.status === '已提交'"
                          class="score-input"
                      ></el-input-number>
                      <div class="score-display">
                        <span class="score-max">当前: {{ reviewForm.economicScore }}/35</span>

                        <!-- 评分标准弹窗 -->
                        <el-popover
                            placement="bottom"
                            width="600"
                            trigger="click"
                            popper-class="criteria-popover"
                        >
                          <div slot="reference" class="criteria-trigger">
                            <i class="el-icon-info-circle"></i> 评分标准
                          </div>
                          <div class="scoring-criteria-popover">
                            <h5 class="criteria-title">评分标准（效益性 - 40%）</h5>
                            <div class="criteria-table-wrapper">
                              <table class="criteria-table">
                                <thead>
                                <tr>
                                  <th>等级</th>
                                  <th>分数范围</th>
                                  <th>评分标准</th>
                                </tr>
                                </thead>
                                <tbody>
                                <tr>
                                  <td colspan="3" class="sub-criteria-title">推广应用情况</td>
                                </tr>
                                <tr>
                                  <td>Ⅰ</td>
                                  <td>9~10分</td>
                                  <td>技术成熟度高，市场需求旺盛，推广应用空间大。</td>
                                </tr>
                                <tr>
                                  <td>Ⅱ</td>
                                  <td>7~8分</td>
                                  <td>技术成熟度较好，市场需求较大，推广应用潜力较好。</td>
                                </tr>
                                <tr>
                                  <td>Ⅲ</td>
                                  <td>5~6分</td>
                                  <td>技术成熟、市场需求和推广应用潜力一般。</td>
                                </tr>
                                <tr>
                                  <td>Ⅳ</td>
                                  <td>0~4分</td>
                                  <td>技术成熟、市场需求和推广应用潜力低。</td>
                                </tr>
                                <tr>
                                  <td colspan="3" class="sub-criteria-title">直接经济效益</td>
                                </tr>
                                <tr>
                                  <td>Ⅰ</td>
                                  <td>9~10分</td>
                                  <td>技术成果实现了显著的经济效益，对产业发展、市场增长或企业盈利产生了重大正面影响。</td>
                                </tr>
                                <tr>
                                  <td>Ⅱ</td>
                                  <td>7~8分</td>
                                  <td>技术成果带来了良好的经济效益，对产业或企业具有实质性的贡献。</td>
                                </tr>
                                <tr>
                                  <td>Ⅲ</td>
                                  <td>5~6分</td>
                                  <td>技术成果具有一定的经济效益，但影响相对有限。</td>
                                </tr>
                                <tr>
                                  <td>Ⅳ</td>
                                  <td>0~4分</td>
                                  <td>技术成果的经济效益不明显，或尚未实现预期的经济效益。</td>
                                </tr>
                                </tbody>
                              </table>
                            </div>
                          </div>
                        </el-popover>
                      </div>
                    </el-form-item>
                  </el-form>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 总分和评审意见 -->
        <div class="review-summary-section">
          <h4 class="section-title">
            <i class="el-icon-star"></i> 评审总结
          </h4>

          <el-form
              ref="reviewForm"
              :model="reviewForm"
              label-width="180px"
              class="review-form"
          >
            <!-- 总分 -->
            <div class="total-score-item">
              <el-form-item label="总分">
                <el-input
                    v-model="reviewForm.totalScore"
                    readonly
                    :disabled="true"
                    style="width: 180px;"
                    suffix="分"
                    class="total-score-input"
                ></el-input>
              </el-form-item>
            </div>

            <!-- 评审意见 -->
            <div class="review-comment-item">
              <el-form-item label="评审意见">
                <el-input
                    v-model="reviewForm.scoreRemark"
                    type="textarea"
                    :rows="4"
                    placeholder="请输入评审意见..."
                    :disabled="currentProject.status === '已提交'"
                ></el-input>
              </el-form-item>
            </div>

            <!-- 操作按钮 -->
            <div class="review-actions">
              <el-button
                  @click="closeReviewDrawer"
                  class="cancel-button"
              >
                关闭
              </el-button>
              <el-button
                  type="success"
                  @click="saveScore"
                  v-if="currentProject.status !== '已提交'"
                  style="margin-left: auto;"
                  :disabled="!canSaveScore"
              >
                保存分数
              </el-button>
            </div>
          </el-form>
        </div>
      </div>
      </el-drawer>

      <!-- 4. 全部提交确认弹窗 -->
      <el-dialog
          title="确认提交全部评审结果"
          :visible.sync="submitAllDialogVisible"
          width="400px"
          top="10%"
      >
        <div class="submit-confirm-content">
          <p>您已完成所有{{ filteredProjects.length }}个项目的评审工作。</p>
          <p>提交后，所有评分将无法修改，请确认是否提交？</p>

          <div class="review-summary">
            <div class="summary-item">
              <span>平均分：</span>
              <span class="summary-value">{{ averageScore.toFixed(1) }}</span>
            </div>
            <div class="summary-item">
              <span>最高分：</span>
              <span class="summary-value">{{ maxScore }}</span>
            </div>
            <div class="summary-item">
              <span>最低分：</span>
              <span class="summary-value">{{ minScore }}</span>
            </div>
          </div>
        </div>
        <div slot="footer">
          <el-button @click="submitAllDialogVisible = false">取消</el-button>
          <el-button
              type="primary"
              @click="confirmSubmitAll"
              :loading="submitLoading"
          >
            确认提交
          </el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { authenticateJudge } from '@/api/judge'
import { getProjectScoreList, saveScore, batchSaveScores } from '@/api/score'

export default {
  name: 'ProjectReview',
  data() {
    return {
      // 登录相关状态
      loginDialogVisible: true,
      loginForm: {
        name: '',
        judgeCode: ''
      },
      loginRules: {
        name: [
          { required: true, message: '请输入评委姓名', trigger: 'blur' }
        ],
        judgeCode: [
          { required: true, message: '请输入评审编码', trigger: 'blur' }
        ]
      },
      loginLoading: false,
      isLogin: false,
      currentUser: {
        name: '',
        expertId: null,
        specialty: ''
      },

      // 项目数据
      allProjects: [],
      filteredProjects: [],

      // 筛选和排序
      filterStatus: 'all',
      searchKeyword: '',
      sortType: 'default',

      // 评审相关
      reviewDrawerVisible: false,
      currentProject: null,
      reviewForm: {
        awardId: null,
        expertId: null,
        bgScore: 0,
        innovationScore: 0,
        economicScore: 0,
        totalScore: 0,
        scoreRemark: '',
        scoreStatus: 2 // 默认为草稿状态
      },

      // 全部提交相关
      submitAllDialogVisible: false,
      submitLoading: false
    };
  },

  computed: {
    // 已评审项目数量
    completedReviewCount() {
      return this.filteredProjects.filter(project => project.status === '已评审' || project.status === '已提交').length;
    },

    // 评审进度百分比
    reviewProgressPercentage() {
      if (this.filteredProjects.length === 0) return 0;
      return Math.round((this.completedReviewCount / this.filteredProjects.length) * 100);
    },

    // 是否所有项目都已评审
    isAllReviewed() {
      return this.filteredProjects.length > 0 &&
          this.completedReviewCount === this.filteredProjects.length;
    },

    // 是否所有项目都已提交
    isAllSubmitted() {
      return this.filteredProjects.length > 0 &&
          this.filteredProjects.every(project => project.status === '已提交');
    },

    // 是否有已评审项目
    hasReviewedProjects() {
      return this.filteredProjects.some(project => project.status === '已评审' || project.status === '已提交');
    },

    // 平均分
    averageScore() {
      const reviewedProjects = this.filteredProjects.filter(p => p.status === '已评审' || p.status === '已提交');
      if (reviewedProjects.length === 0) return 0;

      const total = reviewedProjects.reduce((sum, project) => {
        return sum + parseFloat(project.totalScore);
      }, 0);

      return total / reviewedProjects.length;
    },

    // 最高分
    maxScore() {
      const reviewedProjects = this.filteredProjects.filter(p => p.status === '已评审' || p.status === '已提交');
      if (reviewedProjects.length === 0) return 0;

      return Math.max(...reviewedProjects.map(p => parseFloat(p.totalScore)));
    },

    // 最低分
    minScore() {
      const reviewedProjects = this.filteredProjects.filter(p => p.status === '已评审' || p.status === '已提交');
      if (reviewedProjects.length === 0) return 0;

      return Math.min(...reviewedProjects.map(p => parseFloat(p.totalScore)));
    },

    // 是否可以保存分数（所有分数都已填写）
    canSaveScore() {
      return this.reviewForm.bgScore >= 0 &&
          this.reviewForm.innovationScore >= 0 &&
          this.reviewForm.economicScore >= 0;
    }
  },

  created() {
    // 页面加载时检查是否有保存的登录状态
    this.checkSavedLoginStatus();
  },

  methods: {
    // 检查是否有保存的登录状态
    checkSavedLoginStatus() {
      const savedUser = localStorage.getItem('currentUser');
      if (savedUser) {
        try {
          this.currentUser = JSON.parse(savedUser);
          this.isLogin = true;
          this.loginDialogVisible = false;
          // 重新加载项目信息
          this.fetchProjectList();
        } catch (error) {
          console.error('解析保存的用户信息失败', error);
          // 清除无效的存储数据
          localStorage.removeItem('currentUser');
        }
      }
    },

    // 登录相关方法
    async handleLogin() {
      this.$refs.loginForm.validate(async (valid) => {
        if (valid) {
          this.loginLoading = true;
          try {
            // 调用评委身份验证API
            const response = await authenticateJudge({
              judgeCode: this.loginForm.judgeCode,
              name: this.loginForm.name
            });
            if (response.code === '200') {
              // 验证成功，保存用户信息
              const authData = response.data;
              console.log(authData)
              this.currentUser = {
                name: authData.expertName,
                expertId: authData.expertId,
                specialty: authData.specialty
              };

              // 将用户信息保存到localStorage
              localStorage.setItem('currentUser', JSON.stringify(this.currentUser));

              // 获取项目列表
              await this.fetchProjectList();

              this.isLogin = true;
              this.loginDialogVisible = false;
              this.$message.success(`登录成功，欢迎 ${this.loginForm.name} 评委`);
            } else {
              this.$message.error(response.message || '验证失败');
            }
          } catch (error) {
            console.error('登录失败', error);
            this.$message.error('登录失败，请重试');
          } finally {
            this.loginLoading = false;
          }
        }
      });
    },

    handleUserCommand(command) {
      if (command === 'logout') {
        // 退出登录
        this.$confirm('确定要退出登录吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          // 清除localStorage中的用户信息
          localStorage.removeItem('currentUser');

          this.isLogin = false;
          this.currentUser = { name: '', expertId: null, specialty: '' };
          this.loginForm = { name: '', judgeCode: '' };
          this.loginDialogVisible = true;
          this.allProjects = [];
          this.filteredProjects = [];
          this.$message.success('已退出登录');
        });
      }
    },

    // 获取项目列表
    async fetchProjectList() {
      try {
        const response = await getProjectScoreList({
          expertId: this.currentUser.expertId,
          specialty: this.currentUser.specialty
        });
        if (response.code === '200') {
          // 处理项目数据，转换为前端需要的格式
          this.allProjects = response.data.map(project => {
            // 计算总分
            let totalScore = '-';
            let status = '未评审';

            // 检查是否有分数且不为null
            if (project.bgScore !== null &&
                project.innovationScore !== null &&
                project.economicScore !== null) {
              totalScore = (
                  parseFloat(project.bgScore) +
                  parseFloat(project.innovationScore) +
                  parseFloat(project.economicScore)
              ).toFixed(1);

              // 根据状态判断评审状态
              status = project.scoreStatus === 0 ? '未评审' :
                  project.scoreStatus === 1 ? '已提交' :
                      project.scoreStatus === 2 ? '已评审' : '未知状态';
            }

            return {
              ...project,
              totalScore,
              status
            };
          });
          console.log('allProjects', this.allProjects)
          // 筛选项目
          this.filterProjects();
        } else {
          this.$message.error(response.message || '获取项目列表失败');
        }
      } catch (error) {
        console.error('获取项目列表失败', error);
        this.$message.error('获取项目列表失败，请重试');
      }
    },

    // 项目筛选和排序
    filterProjects() {
      if (!this.currentUser.specialty) return;

      // 基础筛选：只显示当前专业组的项目
      let result = [...this.allProjects];

      // 状态筛选
      if (this.filterStatus === 'unreviewed') {
        result = result.filter(project => project.status === '未评审');
      } else if (this.filterStatus === 'reviewed') {
        result = result.filter(project => project.status === '已评审' || project.status === '已提交');
      }

      // 搜索筛选
      if (this.searchKeyword) {
        const keyword = this.searchKeyword.toLowerCase();
        result = result.filter(project =>
            project.projectName.toLowerCase().includes(keyword)
        );
      }

      // 排序处理
      this.filteredProjects = this.sortProjects(result);
    },

    sortProjects(projects) {
      // 创建副本避免修改原数组
      const sortedProjects = [...projects];

      // 定义申报等级的权重
      const levelWeight = {
        '一等奖': 3,
        '二等奖': 2,
        '三等奖': 1
      };

      switch (this.sortType) {
        case 'level_desc':
          // 按申报等级从高到低
          return sortedProjects.sort((a, b) => {
            return levelWeight[b.declareLevel] - levelWeight[a.declareLevel] || a.awardId - b.awardId;
          });

        case 'level_asc':
          // 按申报等级从低到高
          return sortedProjects.sort((a, b) => {
            return levelWeight[a.declareLevel] - levelWeight[b.declareLevel] || a.awardId - b.awardId;
          });

        case 'score_desc':
          // 按分数从高到低
          return sortedProjects.sort((a, b) => {
            if ((a.status === '已评审' || a.status === '已提交') &&
                (b.status === '已评审' || b.status === '已提交')) {
              return parseFloat(b.totalScore) - parseFloat(a.totalScore) || a.awardId - b.awardId;
            }
            // 已评审项目排在前面
            if (a.status === '已评审' || a.status === '已提交') return -1;
            if (b.status === '已评审' || b.status === '已提交') return 1;
            return a.awardId - b.awardId;
          });

        case 'score_asc':
          // 按分数从低到高
          return sortedProjects.sort((a, b) => {
            if ((a.status === '已评审' || a.status === '已提交') &&
                (b.status === '已评审' || b.status === '已提交')) {
              return parseFloat(a.totalScore) - parseFloat(b.totalScore) || a.awardId - b.awardId;
            }
            // 已评审项目排在前面
            if (a.status === '已评审' || a.status === '已提交') return -1;
            if (b.status === '已评审' || b.status === '已提交') return 1;
            return a.awardId - b.awardId;
          });

        default:
          // 默认顺序（按ID）
          return sortedProjects.sort((a, b) => a.awardId - b.awardId);
      }
    },

    handleFilterChange() {
      this.filterProjects();
    },

    handleSearch() {
      this.filterProjects();
    },

    handleSortChange() {
      this.filterProjects();
    },

    // 表格样式
    tableRowClassName({row}) {
      return (row.status === '已评审' || row.status === '已提交') ? 'reviewed-row' : '';
    },

    getLevelTagType(level) {
      switch (level) {
        case '一等奖':
          return 'primary';
        case '二等奖':
          return 'success';
        case '三等奖':
          return 'info';
        default:
          return 'default';
      }
    },

    // 评审抽屉相关
    openReviewDrawer(project, event) {
      // 阻止事件冒泡（如果从按钮点击）
      if (event) event.stopPropagation();

      this.currentProject = {...project};
      // 添加调试代码
      console.log('当前项目数据:', this.currentProject);
      this.reviewDrawerVisible = true;

      // 初始化评分表单
      this.initReviewForm(project);
    },

    closeReviewDrawer() {
      this.reviewDrawerVisible = false;
      this.currentProject = null;
    },

    initReviewForm(project) {
      this.reviewForm = {
        awardId: project.awardId,
        expertId: project.expertId,
        bgScore: project.bgScore !== null ? parseFloat(project.bgScore) : 0,
        innovationScore: project.innovationScore !== null ? parseFloat(project.innovationScore) : 0,
        economicScore: project.economicScore !== null ? parseFloat(project.economicScore) : 0,
        totalScore: project.totalScore !== '-' ? parseFloat(project.totalScore) : 0,
        scoreRemark: project.scoreRemark || '',
        scoreStatus: project.scoreStatus || 2 // 使用项目本身的状态
      };
    },

    calculateTotalScore() {
      this.reviewForm.totalScore = (
          this.reviewForm.bgScore +
          this.reviewForm.innovationScore +
          this.reviewForm.economicScore
      ).toFixed(1);
    },

    async saveScore() {
      try {
        // 准备提交的数据
        const scoreData = {
          awardId: this.reviewForm.awardId,
          expertId: this.reviewForm.expertId,
          bgScore: this.reviewForm.bgScore,
          innovationScore: this.reviewForm.innovationScore,
          economicScore: this.reviewForm.economicScore,
          scoreRemark: this.reviewForm.scoreRemark,
          scoreStatus: this.currentProject.status === '已提交' ? 1 : 2 // 保持已提交状态或设为已评审
        };

        // 调用保存API
        const response = await saveScore(scoreData);
        if (response.code === '200') {
          // 更新本地项目数据
          const projectIndex = this.allProjects.findIndex(p => p.awardId === this.reviewForm.awardId);
          if (projectIndex !== -1) {
            this.allProjects[projectIndex] = {
              ...this.allProjects[projectIndex],
              bgScore: this.reviewForm.bgScore,
              innovationScore: this.reviewForm.innovationScore,
              economicScore: this.reviewForm.economicScore,
              totalScore: this.reviewForm.totalScore,
              scoreRemark: this.reviewForm.scoreRemark,
              scoreStatus: scoreData.scoreStatus,
              status: scoreData.scoreStatus === 1 ? '已提交' : '已评审'
            };
          }
          // 更新筛选后的列表
          this.filterProjects();

          // 关闭抽屉并提示
          this.closeReviewDrawer();
          this.$message.success('评分已保存成功');
        } else {
          this.$message.error(response.message || '保存失败');
        }
      } catch (error) {
        console.error('保存评分失败', error);
        this.$message.error('保存评分失败，请重试');
      }
    },

    // 全部提交相关
    submitAllReviews() {
      if (this.isAllReviewed) {
        this.submitAllDialogVisible = true;
      }
    },

    async confirmSubmitAll() {
      this.submitLoading = true;
      try {
        // 准备批量提交的数据，将所有项目状态改为1（已提交）
        const scoreList = this.filteredProjects.map(project => ({
          awardId: project.awardId,
          expertId: project.expertId,
          bgScore: project.bgScore,
          innovationScore: project.innovationScore,
          economicScore: project.economicScore,
          scoreRemark: project.scoreRemark || '',
          scoreStatus: 1 // 全部改为已提交状态
        }));

        // 调用批量保存API
        const response = await batchSaveScores(scoreList);

        if (response.code === '200') {
          // 更新本地项目状态
          this.allProjects = this.allProjects.map(project => {
            // 只更新当前筛选列表中的项目
            const isInFilteredList = this.filteredProjects.some(p => p.awardId === project.awardId);
            return isInFilteredList
                ? {...project, scoreStatus: 1, status: '已提交'}
                : project;
          });

          this.filterProjects();
          this.submitAllDialogVisible = false;
          this.$message.success('所有评审结果已成功提交！');
        } else {
          this.$message.error(response.message || '批量提交失败');
        }
      } catch (error) {
        console.error('批量提交失败', error);
        this.$message.error('批量提交失败，请重试');
      } finally {
        this.submitLoading = false;
      }
    }
  }
};
</script>

<style scoped>
.review-system-container {
  font-family: 'Helvetica Neue', Arial, sans-serif;
  background-color: #f5f7fa;
  min-height: 100vh;
}

/* 登录表单样式 */
.login-form {
  margin-top: 20px;
}

/* 顶部导航 */
.top-nav {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #1890ff;
  color: white;
  padding: 0 20px;
  height: 60px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.logo-title h1 {
  font-size: 1.5rem;
  margin: 0;
  font-weight: 600;
}

.user-info-container {
  margin-left: auto;
}

.user-info {
  display: inline-flex;
  align-items: center;
  cursor: pointer;
  padding: 5px 10px;
  border-radius: 4px;
  transition: background-color 0.2s;
  color: white;
}

.user-info:hover {
  background-color: rgba(255, 255, 255, 0.1);
}

.user-info .el-icon-user-circle {
  font-size: 1.2rem;
  margin-right: 8px;
  color: white;
}

.username {
  margin-right: 8px;
  color: white;
}

.specialty-tag {
  background-color: rgba(255, 255, 255, 0.2);
  padding: 2px 8px;
  border-radius: 12px;
  font-size: 0.8rem;
  margin-right: 8px;
  color: white;
}

.user-info .el-icon-arrow-down {
  color: white;
}

/* 页面标题 */
.page-header {
  padding: 20px;
  border-bottom: 1px solid #e8e8e8;
  background-color: white;
}

.page-header h2 {
  margin: 0 0 10px 0;
  color: #1f2329;
}

.page-description {
  margin: 0;
  color: #86909c;
  font-size: 0.9rem;
}

/* 筛选和排序栏 */
.filter-sort-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  background-color: white;
  border-bottom: 1px solid #e8e8e8;
  flex-wrap: wrap;
  gap: 10px;
}

.filter-group {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
}

.sort-group {
  display: flex;
  align-items: center;
}

/* 评审进度 */
.review-progress {
  display: flex;
  align-items: center;
  padding: 15px 20px;
  background-color: white;
  border-bottom: 1px solid #e8e8e8;
}

.progress-info {
  display: flex;
  align-items: center;
  margin-right: 15px;
  white-space: nowrap;
}

.completed-count {
  color: #1890ff;
  font-weight: bold;
  margin: 0 3px;
}

.total-count {
  font-weight: bold;
  margin: 0 3px;
}

/* 项目列表 */
.project-list-container {
  padding: 20px;
}

.reviewed-score {
  color: #52c41a;
  font-weight: bold;
}

.unreviewed-score {
  color: #86909c;
}

.empty-state {
  padding: 40px 0;
  text-align: center;
  background-color: white;
  border-radius: 4px;
}

/* 评审抽屉优化样式 */
.review-drawer-content {
  padding: 20px;
  height: 100%;
  overflow-y: auto;
  box-sizing: border-box;
}

/* 1. 优化的抽屉头部样式 */
.drawer-header {
  margin-bottom: 25px;
  padding-bottom: 15px;
  border-bottom: 1px solid #e8e8e8;
}

.drawer-title {
  margin: 0 0 10px 0;
  color: #1f2329;
  font-size: 1.2rem;
}

.project-info-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.project-name {
  font-weight: 500;
  color: #1f2329;
  max-width: 70%;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.project-status-tag {
  margin-top: 0;
}

.review-section {
  margin-bottom: 40px;
  padding-bottom: 20px;
  border-bottom: 1px solid #f0f0f0;
}

.review-section:last-child {
  border-bottom: none;
}

.review-section-content {
  margin-top: 15px;
}

.section-title {
  font-size: 1rem;
  color: #1890ff;
  margin-bottom: 12px;
  display: flex;
  align-items: center;
}

.section-title i {
  margin-right: 8px;
}

/* 内容与评分项组合容器 */
.content-score-container {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  margin-bottom: 25px;
}

.detail-card {
  flex: 1;
  min-width: 300px;
  border-radius: 4px;
  max-height: 300px;
  overflow-y: auto;
}

.detail-card p {
  line-height: 1.8;
  margin: 0;
  color: #4e5969;
}

/* 添加预格式化文本样式以支持换行 */
.preformatted-text {
  white-space: pre-wrap;
  word-wrap: break-word;
}

/* 评分面板样式 */
.score-panel {
  width: 350px;
  background-color: #fafafa;
  padding: 15px;
  border-radius: 6px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

/* 数字输入框样式 */
.score-input {
  width: 100%;
  margin-bottom: 10px;
}

.current-score {
  color: #1890ff;
  font-weight: bold;
  font-size: 1.1rem;
}

/* 评分区域 */
.review-form {
  margin-top: 10px;
}

.score-item {
  margin-bottom: 15px;
}

.score-display {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
  align-items: center;
}

.current-score-text {
  color: #1890ff;
  font-weight: 500;
}

.score-max {
  color: #86909c;
  font-size: 0.9rem;
}

/* 2. 优化的评分标准弹窗样式 */
.criteria-trigger {
  color: #1890ff;
  cursor: pointer;
  font-size: 0.9rem;
  display: flex;
  align-items: center;
}

.criteria-trigger i {
  margin-right: 5px;
}

.criteria-popover {
  max-height: 500px;
  overflow-y: auto;
}

.scoring-criteria-popover {
  padding: 10px;
}

.criteria-title {
  margin: 0 0 15px 0;
  color: #1f2329;
  font-size: 0.95rem;
  font-weight: 600;
}

.criteria-table-wrapper {
  overflow-x: auto;
}

.criteria-table {
  width: 100%;
  border-collapse: collapse;
  font-size: 0.9rem;
}

.criteria-table th,
.criteria-table td {
  border: 1px solid #e8e8e8;
  padding: 10px 12px;
  text-align: left;
}

.criteria-table th {
  background-color: #e6f7ff;
  color: #1890ff;
  font-weight: 500;
  white-space: nowrap;
}

.criteria-table tr:nth-child(even) {
  background-color: #f9f9f9;
}

.criteria-table .sub-criteria-title {
  background-color: #fffbe6;
  color: #faad14;
  font-weight: 500;
  text-align: center;
}

.total-score-item {
  margin: 25px 0;
  padding-top: 15px;
  border-top: 1px dashed #e8e8e8;
}

.total-score-input {
  font-size: 1.2rem;
  color: #1890ff;
  font-weight: bold;
}

.review-comment-item {
  margin-bottom: 25px;
}

.review-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 30px;
  padding-top: 15px;
  border-top: 1px solid #e8e8e8;
}

.cancel-button {
  margin-right: 10px;
}

/* 全部提交确认弹窗 */
.submit-confirm-content {
  margin-bottom: 15px;
}

.review-summary {
  display: flex;
  justify-content: space-between;
  margin-top: 20px;
  padding-top: 15px;
  border-top: 1px dashed #e8e8e8;
}

.summary-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  flex: 1;
}

.summary-value {
  font-size: 1.2rem;
  font-weight: bold;
  color: #1890ff;
  margin-top: 5px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .content-score-container {
    flex-direction: column;
  }

  .score-panel {
    width: 100%;
  }

  .filter-sort-bar {
    flex-direction: column;
    align-items: flex-start;
  }

  .sort-group {
    width: 100%;
    margin-top: 10px;
  }

  .criteria-table th,
  .criteria-table td {
    padding: 8px 10px;
    font-size: 0.85rem;
  }
}
</style>
